package com.team9.fitness.controller;

import com.team9.fitness.dto.SignInDTO;
import com.team9.fitness.dto.SignUpDTO;
import com.team9.fitness.service.ZRDDSSendService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = { "*" }, allowCredentials = "false")
@Tag(name = "用户管理", description = "用户登录、注册等认证相关接口")
@Slf4j
public class UserController {

        @Autowired
        private ZRDDSSendService zrddsSendService;

        /**
         * 用户登录
         */
        @Operation(summary = "用户登录", description = "通过用户名和密码进行用户登录认证")
        @ApiResponses(value = {
                        @ApiResponse(responseCode = "200", description = "登录成功"),
                        @ApiResponse(responseCode = "400", description = "请求参数错误"),
                        @ApiResponse(responseCode = "500", description = "服务器内部错误")
        })
        @PostMapping("/signIn")
        public CompletableFuture<ResponseEntity<Map<String, Object>>> signIn(
                        @Parameter(description = "登录信息", required = true) @RequestBody SignInDTO signInDTO) {

                log.info("用户登录请求: username={}", signInDTO.getUsername());

                return zrddsSendService.sendUserLoginRequest(signInDTO.getUsername(), signInDTO.getPassword())
                                .thenApply(response -> {
                                        Map<String, Object> result = new HashMap<>();
                                        if (response.getSuccess()) {
                                                // 检查 data 中是否包含实际的业务结果
                                                Map<String, Object> data = (Map<String, Object>) response.getData();
                                                if (data != null && data.containsKey("success")) {
                                                        // data 中包含业务结果，直接使用
                                                        Boolean businessSuccess = (Boolean) data.get("success");
                                                        if (businessSuccess) {
                                                                result.put("success", true);
                                                                result.put("message", data.get("message"));
                                                                result.put("user", data.get("user"));
                                                                log.info("用户登录成功: username={}",
                                                                                signInDTO.getUsername());
                                                        } else {
                                                                result.put("success", false);
                                                                result.put("message", data.get("message"));
                                                                log.warn("用户登录失败: username={}, error={}",
                                                                                signInDTO.getUsername(),
                                                                                data.get("message"));
                                                        }
                                                } else {
                                                        // data 中没有业务结果，使用默认成功响应
                                                        result.put("success", true);
                                                        result.put("message", "登录成功");
                                                        result.put("data", response.getData());
                                                        log.info("用户登录成功: username={}", signInDTO.getUsername());
                                                }
                                        } else {
                                                result.put("success", false);
                                                result.put("message",
                                                                response.getMessage() != null ? response.getMessage()
                                                                                : "登录失败");
                                                log.warn("用户登录失败: username={}, error={}", signInDTO.getUsername(),
                                                                response.getError());
                                        }
                                        return ResponseEntity.ok(result);
                                })
                                .exceptionally(throwable -> {
                                        log.error("用户登录异常: username={}", signInDTO.getUsername(), throwable);
                                        Map<String, Object> result = new HashMap<>();
                                        result.put("success", false);
                                        result.put("message", "登录服务异常，请稍后重试");
                                        return ResponseEntity.ok(result);
                                });
        }

        /**
         * 用户注册
         */
        @Operation(summary = "用户注册", description = "创建新的用户账户")
        @ApiResponses(value = {
                        @ApiResponse(responseCode = "200", description = "注册成功"),
                        @ApiResponse(responseCode = "400", description = "请求参数错误"),
                        @ApiResponse(responseCode = "409", description = "用户名已存在"),
                        @ApiResponse(responseCode = "500", description = "服务器内部错误")
        })
        @PostMapping("/signUp")
        public CompletableFuture<ResponseEntity<Map<String, Object>>> signUp(
                        @Parameter(description = "注册信息", required = true) @RequestBody SignUpDTO signUpDTO) {

                log.info("用户注册请求: username={}", signUpDTO.getUsername());

                return zrddsSendService
                                .sendUserRegisterRequest(signUpDTO.getUsername(), signUpDTO.getPassword(),
                                                signUpDTO.getConfirmPassword())
                                .thenApply(response -> {
                                        Map<String, Object> result = new HashMap<>();
                                        if (response.getSuccess()) {
                                                result.put("success", true);
                                                result.put("message", "注册成功");
                                                result.put("data", response.getData());
                                                log.info("用户注册成功: username={}", signUpDTO.getUsername());
                                        } else {
                                                result.put("success", false);
                                                result.put("message",
                                                                response.getMessage() != null ? response.getMessage()
                                                                                : "注册失败");
                                                log.warn("用户注册失败: username={}, error={}", signUpDTO.getUsername(),
                                                                response.getError());
                                        }
                                        return ResponseEntity.ok(result);
                                })
                                .exceptionally(throwable -> {
                                        log.error("用户注册异常: username={}", signUpDTO.getUsername(), throwable);
                                        Map<String, Object> result = new HashMap<>();
                                        result.put("success", false);
                                        result.put("message", "注册服务异常，请稍后重试");
                                        return ResponseEntity.ok(result);
                                });
        }

        /**
         * 根据ID获取用户信息
         */
        @GetMapping("/{id}")
        public CompletableFuture<ResponseEntity<Map<String, Object>>> getUserById(@PathVariable Long id) {

                log.info("根据ID获取用户信息请求: id={}", id);

                return zrddsSendService.sendBusinessRequest("USER_GET_BY_ID", "GET", "/api/user/" + id,
                                id.toString(), new HashMap<>())
                                .thenApply(response -> {
                                        Map<String, Object> result = new HashMap<>();
                                        if (response.getSuccess()) {
                                                result.put("success", true);
                                                result.put("data", response.getData());
                                                log.info("获取用户信息成功: id={}", id);
                                        } else {
                                                result.put("success", false);
                                                result.put("message",
                                                                response.getMessage() != null ? response.getMessage()
                                                                                : "用户不存在");
                                                log.warn("获取用户信息失败: id={}, error={}", id, response.getError());
                                        }
                                        return ResponseEntity.ok(result);
                                })
                                .exceptionally(throwable -> {
                                        log.error("获取用户信息异常: id={}", id, throwable);
                                        Map<String, Object> result = new HashMap<>();
                                        result.put("success", false);
                                        result.put("message", "获取用户信息服务异常，请稍后重试");
                                        return ResponseEntity.ok(result);
                                });
        }
}
